package com.tudouji.project.bill.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.project.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tudouji.project.bill.mapper.AutoTransferMapper;
import com.tudouji.project.bill.domain.AutoTransfer;
import com.tudouji.project.bill.service.IAutoTransferService;

/**
 * 自动调拨Service业务层处理
 * 
 * @author tudouji
 * @date 2023-08-30
 */
@Service
public class AutoTransferServiceImpl implements IAutoTransferService 
{
    @Autowired
    private AutoTransferMapper autoTransferMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询自动调拨
     * 
     * @param id 自动调拨ID
     * @return 自动调拨
     */
    @Override
    public AutoTransfer selectAutoTransferById(Long id)
    {
        return autoTransferMapper.selectAutoTransferById(id);
    }

    /**
     * 查询自动调拨列表
     * 
     * @param autoTransfer 自动调拨
     * @return 自动调拨
     */
    @Override
    public List<AutoTransfer> selectAutoTransferList(AutoTransfer autoTransfer)
    {
        return autoTransferMapper.selectAutoTransferList(autoTransfer);
    }

    /**
     * 查询到当前采收组织（调出组织）入库库房（调出库房）所对应的地头直销目标库，逻辑是：
     *     找到调出组织、调出库房对应的auto_transfer记录 A，找到A的下一条记录（A.sort+1)
     *     B，如果A的调入组织、调入库房=B的调出组织、调出库房，则B匹配成功，返回B
     *
     * @param autoTransfer
     * @return
     */
    @Override
    public AutoTransfer findDestAutoTransfer(AutoTransfer autoTransfer) {
//        int transCount = Integer.valueOf(sysConfigService.selectConfigByKey("direct_sales_count"));
//

        AutoTransfer result;
        //不中转的,当前组织、当前库房直接出库
        autoTransfer.setToOrguid(autoTransfer.getFromOrgguid());
        autoTransfer.setToStrmguid(autoTransfer.getFromStrmguid());
        result = autoTransfer;

        String directSaleGropup=null;
        String lastToOrgguid="empty",lastToStrmguid="empty";
        boolean matched=false;
        List<AutoTransfer> autoTransfers = selectAutoTransferList(new AutoTransfer());
        //遍历所有的auto_transfer
        for(int i=0;i<autoTransfers.size();i++){
            AutoTransfer item = autoTransfers.get(i);
            if((item.getFromOrgguid().equals(autoTransfer.getFromOrgguid())
               && item.getFromStrmguid().equals(autoTransfer.getFromStrmguid())
                && isDtzx(item))
               || matched){
                //找到当前调出组织、调出库房所配置的一条针对“地头直销”的记录
                matched=true;
                if(directSaleGropup!=null&&!directSaleGropup.equals(item.getDirectSaleGroup())){
                    break;
                }

                if(!lastToOrgguid.equals("empty")&&(!lastToOrgguid.equals(item.getFromOrgguid())
                 && (!lastToStrmguid.equals(item.getFromStrmguid())))){
                    throw new CustomException("自动中转配置异常,不连续！");
                }
                result = item;
                directSaleGropup = item.getDirectSaleGroup();
                lastToOrgguid = item.getToOrguid();
                lastToStrmguid=item.getToStrmguid();

            }
        }
        return result;
    }

    /**
     * 获取针对地头直销配置的自动调拨信息
     * @param autoTransfer
     * @return
     */
    @Override
    public AutoTransfer findAutoTransfer(AutoTransfer autoTransfer) {
        List<AutoTransfer> autoTransfers = selectAutoTransferList(autoTransfer);
        for(AutoTransfer item :autoTransfers){
            if(isDtzx(item)){
                return item;
            }
        }
        return null;
    }

    private boolean isDtzx(AutoTransfer autoTransfer){
        return autoTransfer.getDirectSaleGroup()!=null && autoTransfer.getDirectSaleGroup().toLowerCase().startsWith("dtzx");
    }


    /**
     * 新增自动调拨
     * 
     * @param autoTransfer 自动调拨
     * @return 结果
     */
    @Override
    public int insertAutoTransfer(AutoTransfer autoTransfer)
    {
        autoTransfer.setCreateTime(DateUtils.getNowDate());
        return autoTransferMapper.insertAutoTransfer(autoTransfer);
    }

    /**
     * 修改自动调拨
     * 
     * @param autoTransfer 自动调拨
     * @return 结果
     */
    @Override
    public int updateAutoTransfer(AutoTransfer autoTransfer)
    {
        autoTransfer.setUpdateTime(DateUtils.getNowDate());
        return autoTransferMapper.updateAutoTransfer(autoTransfer);
    }

    /**
     * 批量删除自动调拨
     * 
     * @param ids 需要删除的自动调拨ID
     * @return 结果
     */
    @Override
    public int deleteAutoTransferByIds(Long[] ids)
    {
        return autoTransferMapper.deleteAutoTransferByIds(ids);
    }

    /**
     * 删除自动调拨信息
     * 
     * @param id 自动调拨ID
     * @return 结果
     */
    @Override
    public int deleteAutoTransferById(Long id)
    {
        return autoTransferMapper.deleteAutoTransferById(id);
    }
}
